//import axios from 'axios';
import globalConfig from './config';
import _data from "./_data";
import mixins from "./mixins";
import _action from "./_action";

const uni_request = (config) => {
    return new Promise((resolve, reject) => {
        let header = {
            /** 这里设置为简单跨域，只会请求一次 */
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': "Bearer " + _data.localData('token')
        };
        let data = ('data' in config) ? config.data : {},
            url = globalConfig.api_url + config.url;
        console.log(url, data)
        uni.request({
            url: url,
            data: data,
            method: ('type' in config ? config.type : 'POST'),
            header: header,
            dataType: 'json',
            success(response) {
                if(response.data.success || response.data.code==200){
                    resolve(response.data)
                }else{
                    reject(response.data)
                }
            },
            fail(error) {
                if (error.response.status == 401) {
                    //token 过期
                    _data.data('token', null);
                    _action.checkFail();
                    return
                }
                reject(error.response.data)
            },
            complete() {
                //uni.hideLoading();
            }
        });
    })
}
let request = {
    get(url, data) {
        return uni_request({
            type: 'get',
            url: url,
            data: data || {}
        });
    },
    post(url, data) {
        return uni_request({
            type: 'post',
            url: url,
            data: data
        });
    },
    request(config) {
        return uni_request(config)
    },
    file(config) {
        if (!config) {
            config = {};
        }
        let send_data = ('data' in config) ? config.data : {}
        let header = {
            'Authorization': "Bearer " + _data.localData('token')
        };
        return new Promise((resolve, reject) => {

            let uploadTask = uni.uploadFile({
                url: globalConfig.api_url + '/chat/upload',
                type: ('type' in config) ? config.type : '',
                header: header,
                name: 'file',
                /** formData必须要有值，否则会上传失败 */
                formData: send_data,
                success: (res) => {
                    resolve(res.data)
                },
                fail: (err) => {
                    reject(err)
                }
            });

            uploadTask.onProgressUpdate((res) => {
                if ('onProgressUpdate' in config) {
                    config.onProgressUpdate();
                }
                return;
                console.log('上传进度' + res.progress);
                console.log('已经上传的数据长度' + res.totalBytesSent);
                console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
            });
        })

    }
}
/**
 let instance = axios.create({
	headers: {
		'content-type': 'application/x-www-form-urlencoded'
	},
	baseURL: globalConfig.api_url
})

 // http request 拦截器
 instance.interceptors.request.use(
 config => {
		const token = _data.data('token');
		if (token) { // 判断是否存在token，如果存在的话，则每个http header都加上token
			config.headers['Authorization'] = "Bearer " + token //请求头加上token
			config.data.token = token;
		}
		return config
	},
 err => {
		return Promise.reject(err)
	})

 // http response 拦截器
 instance.interceptors.response.use(
 response => {
		//拦截响应，做统一处理
		if (response.data.code) {
			switch (response.data.code) {
				case 401:
					_data.data('token', '');
					_action.checkFail();
			}
		}
		return response.data
	},
 //接口错误状态处理，也就是说无响应时的处理
 error => {
		return Promise.reject(error.response.status) // 返回接口返回的错误信息
	})
 **/
export default request
